package com.hupu.jrs.service

import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import com.hupu.jrs.AppManager
import com.hupu.jrs.Logger
import com.hupu.jrs.MyApplication
import com.hupu.jrs.R
import com.hupu.jrs.api.forum.ForumApi
import com.hupu.jrs.bean.Message
import com.hupu.jrs.bean.MessageData
import com.hupu.jrs.bean.MessageResult
import com.hupu.jrs.components.storage.UserStorage
import com.hupu.jrs.injector.module.ServiceModule
import com.hupu.jrs.ui.messagelist.MessageActivity
import com.hupu.jrs.ui.splash.SplashActivity
import com.hupu.jrs.util.NetWorkUtil
import com.hupu.jrs.util.SettingPrefUtil
import java.util.Calendar
import javax.inject.Inject
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1

/**
 * Created by sll on 2016/3/16.
 */
class MessageService : Service() {

    @Inject
    internal var mUserStorage: UserStorage? = null
    @Inject
    internal var mForumApi: ForumApi? = null

    private var notificationManager: NotificationManager? = null

    private val operation: PendingIntent
        get() {
            val intent = Intent()
            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
            intent.action = ACTION_GET
            return PendingIntent.getService(baseContext, 1000, intent, PendingIntent.FLAG_CANCEL_CURRENT)
        }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        Logger.d("服务初始化")
        DaggerServiceComponent.builder()
                .serviceModule(ServiceModule(this))
                .applicationComponent((application as MyApplication).applicationComponent)
                .build()
                .inject(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (!mUserStorage!!.isLogin || !SettingPrefUtil.getNotification(this)) {
            stopSelf()
            return super.onStartCommand(intent, flags, startId)
        }

        if (notificationManager == null) {
            notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        }

        val action = if (intent != null) intent.action else ""

        if (ACTION_GET == action) {
            resetTheTime()
            loadMessage()
        } else if (ACTION_UPDATE == action) {
            Logger.d("刷新时间")
            resetTheTime()
        } else if (ACTION_CLOSE == action) {
            clearAlarm()
            stopSelf()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    private fun clearAlarm() {
        val am = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        am.cancel(operation)
    }

    private fun resetTheTime() {
        Logger.d("resetTheTime")

        val am = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        // 指定时间
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = System.currentTimeMillis()
        calendar.add(Calendar.HOUR, 1)
        am.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, operation)
    }

    private fun loadMessage() {
        if (!NetWorkUtil.isWifiConnected(this)) {
            return
        }
        mForumApi!!.getMessageList("", 1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ messageData ->
                    if (messageData != null && messageData.status == 200) {
                        notifyMessageCount(messageData.result)
                    }
                }) { }
    }

    fun notifyMessageCount(result: MessageResult?) {
        for (message in result!!.list!!) {
            val builder = NotificationCompat.Builder(this)
            builder.setSmallIcon(R.drawable.ic_list_comment)
                    .setContentTitle(message.info)
                    .setContentText("来自TLint")
            val intent: Intent
            if (AppManager.appManager.isAppExit) {
                intent = Intent(this, SplashActivity::class.java)
                intent.action = Intent.ACTION_MAIN
                intent.addCategory(Intent.CATEGORY_LAUNCHER)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                intent.action = SplashActivity.ACTION_NOTIFICATION_MESSAGE
            } else {
                intent = Intent(this, MessageActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            val contentIntent = PendingIntent.getActivity(this, Integer.valueOf(message.id)!!, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT)
            builder.setContentIntent(contentIntent).setAutoCancel(true)
            builder.setTicker(message.info)

            notificationManager!!.notify(Integer.valueOf(message.id)!!, builder.build())
        }
    }

    companion object {


        val ACTION_GET = "com.gzsll.hupu.ACTION_GET"
        val ACTION_UPDATE = "com.gzsll.hupu.ACTION_UPDATE"
        val ACTION_CLOSE = "com.gzsll.hupu.ACTION_CLOSE"
    }
}
